/* A simple server in the internet domain using TCP
   The port number is passed as an argument */
#include <string>
#include <iostream>
#include <cerrno>
#include <cstring>
#include <cstdlib>

#include <sys/types.h> 
#include <sys/socket.h>
#include <netinet/in.h>

int main(int argc, char *argv[])
{
        if (argc < 2) {
                std::cerr << "ERROR, no port provided" << std::endl;
                return 1;
        }
        //creates new socket IPv4 TCP and stores descriptor in sockfd
        int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (sockfd < 0) {
                std::cerr << "ERROR opening socket" << std::endl;
                return 1;
        }

        //Creates and initializes sock_addr_in structure.
        sockaddr_in serv_addr;
        memset(&serv_addr, 0, sizeof(sockaddr_in));
        serv_addr.sin_family = AF_INET;
        serv_addr.sin_addr.s_addr = INADDR_ANY;
        // htons converts 16bit integer to network byte order.
        int portno = atoi(argv[1]);
        serv_addr.sin_port = htons(portno);

        if(bind(sockfd, (sockaddr*)&serv_addr, sizeof(serv_addr)) < 0) {
                std::cerr << "Can't bind socket: errno " << errno << std::endl;
                return 1;
        }
        // Start listening for incoming connections, 5 is size of backlog queue.
        listen(sockfd, 5);

        for(int i = 1; i <= 20; i++)
        {
                uint16_t r;
                int n = read(sockfd, &r, sizeof(uint16_t));
                if (n < 0) {
                        std::cerr << "Error reading from socket" << std::endl;
                        return 1;
                }
                int x = ntohs(r);
                std::cout << x << std::endl;
        }

        close(sockfd);
        return 0; 
}
